/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2018年10月06日
*   描    述：
*   
================================================================*/


#include <iostream>

using namespace std;

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    ListNode * rotateRight(ListNode * head, int k) {
        // write your code here
        if( head == NULL || k <= 0 )
            return head;
        int len = 1;
        ListNode *p = head;
        while( p->next ){
            p = p->next;
            len++;
        }

        p->next = head;
        p = head;
        k = k%len;
        int step = len - k;
        while( --step > 0 ){
            p = p->next;
        }
        
        ListNode *tmp = p->next;
        p->next = NULL;
        
        return tmp;
    }
};